package com.desktopmng.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.config.Result;
import org.apache.struts2.config.Results;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.desktopmng.core.ServiceManager;
import com.desktopmng.core.utils.Json;
import com.desktopmng.exception.JFossException;
import com.desktopmng.orm.DesktopContent;
import com.desktopmng.orm.UserConfig;
import com.desktopmng.orm.UserToDstc;
import com.desktopmng.service.DesktopContentManager;
import com.desktopmng.service.UserConfigManager;
import com.desktopmng.service.UserToDstcManager;

@SuppressWarnings("serial")
@Results( {
		@Result(value = "/common/message.jsp"),
		@Result(name = "delInfo", value = "/jfoss2/desktop/userconfig/editSucess.jsp"),
		@Result(name = "modifyInfo", value = "/resources/jsp/index.jsp"),
		@Result(name = "searchinfoinit", value = "/jfoss2/desktop/userconfig/editUserConfig.jsp"),
		@Result(name = "viewInfo", value = "${indexPage}") })
@Json
public class UserConfigAction extends BaseJsonAction {


	private String indexPage;


	private UserToDstcManager userToDstcManager = (UserToDstcManager) ServiceManager
			.getBean("userToDstcManager");

	private DesktopContentManager desktopContentManager = (DesktopContentManager) ServiceManager
			.getBean("desktopContentManager");

	private UserConfigManager userConfigManager = (UserConfigManager) ServiceManager
			.getBean("userConfigManager");


	/**
	 * 更改个人配置，并将修改数据库
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public String addInfo() throws Exception {

		String ms_Id = request.getParameter("ms_Id");
//		User user = (User) request.getSession().getAttribute("USER");
		UserConfig userconfig1 = (UserConfig) request.getSession()
				.getAttribute("USERCONFIG");
		try {
			if (ms_Id != null) {
				userconfig1.setMsId(new Long(ms_Id));
			}
			Properties prop = new Properties();
//			userconfig1.setUserId(user.getId());
//			prop.setProperty("userId", user.getId().toString());
			if (userConfigManager.findUserConfigByCondition(prop) != null) {
				userConfigManager.updateUserConfig(userconfig1);
			} else {

				if (userToDstcManager.findUserToDstcByCondition(prop) != null) {
					List list = userToDstcManager
							.findUserToDstcByCondition(prop);
					String template = "";
					for (int i = 0; i < list.size(); i++) {
						UserToDstc userToDstc = (UserToDstc) list.get(i);
						Long DstcId = userToDstc.getDstcId();
						if (i == list.size() - 1) {
							template = template + DstcId + "," + "&";
						} else {
							template = template + DstcId + ",";
						}
					}
//					userconfig1.setLayout(Constants.DEFAULT_LAYOUT);
					userconfig1.setTemplate(template);
				}

				userConfigManager.addUserConfig(userconfig1);
			}

			String layoutNumber = request.getParameter("layout");
			if (layoutNumber != null) {

				userconfig1 = userConfigManager.updateUserConfigByLayoutNumber(
						userconfig1, Integer.parseInt(layoutNumber));
				userConfigManager.updateUserConfig(userconfig1);

			}
			request.getSession().setAttribute("USERCONFIG", userconfig1);

		} catch (JFossException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		Struts2Utils.renderJson("{\"flag\":\"1\",\"msg\":\"保存成功\"}");
		return null;
	}

	// 加载用户配置，进入IGOOGLE主页

	public String modifyInfo() throws Exception {

//		User user = (User) request.getSession().getAttribute("USER");

		UserConfig userConfig = userConfigManager.findUserConfigByUserId(382l);
		Properties prop = new Properties();

//		prop.setProperty("userId", user.getId().toString());
		List<DesktopContent> dstcList = new ArrayList<DesktopContent>();
		Set<DesktopContent> dstcSet = new HashSet<DesktopContent>();
		try {
			Map<Long, DesktopContent> map = new HashMap<Long, DesktopContent>();
			List list2 = desktopContentManager.findDesktopContentByCondition(null);
			for (int i=0;i<list2.size();i++) {
				DesktopContent desktop = (DesktopContent) list2.get(i);
				map.put(desktop.getId(), desktop);
			}
			List list = userToDstcManager.findUserToDstcByCondition(prop);
			if (list != null) {
				for (int i = 0; i < list.size(); i++) {
					UserToDstc userToDstc = (UserToDstc) list.get(i);
					Long dstcId = userToDstc.getDstcId();
					DesktopContent desktop = map.get(dstcId);
					if (desktop != null)
						dstcSet.add(desktop);
				}
				// 害怕有重复，先取到SET里
				Iterator it = dstcSet.iterator();
				while (it.hasNext()) {
					dstcList.add((DesktopContent) it.next());
				}

				Document document = DocumentHelper.createDocument();
				Element layout = document.addElement("layout");
				for (int i = 0; i < dstcList.size(); i++) {
					DesktopContent desk = (DesktopContent) dstcList.get(i);
					Element container = layout.addElement("container"
							+ desk.getId());
					Element title = container
							.addElement("title" + desk.getId());
					title.setText(desk.getDstcName());
					//System.out.println(desk.getId());
					Element memo = container.addElement("memo" + desk.getId());
					memo.setText(desk.getId().toString());
					Element id = container.addElement("id" + desk.getId());
					id.setText(desk.getId().toString());
					Element titleurl = container.addElement("titleurl" + desk.getId());
					titleurl.setText(StringUtils.defaultIfEmpty(desk.getTitleUrl(), ""));
					//判断链接打开的目标，即为a的target属性
					Element target = container.addElement("target" + desk.getId());
					target.setText(StringUtils.defaultIfEmpty(desk.getJsContent(), ""));
				}
				String strLayout = userConfig.getLayout();// UserConfig对象的布局信息。例如：33%；33%；33%
				int lineNumber = strLayout.split(";").length;
				String lay = "containerLayout=" + userConfig.getTemplate();// UserConfig对象的布局详情
				// 例如：2,12,&9,&3,&
				request.setAttribute("template", strLayout);
				request.setAttribute("document", document.asXML().replaceFirst(
						"\n", "").replaceAll("\"", "\\\\\""));
				request.setAttribute("currentLayout", lay);
				//System.out.println(document.asXML().replaceFirst("\n", ""));
				request.setAttribute("list", list);
				request.setAttribute("lineNumber", lineNumber);
			}
		} catch (JFossException e) {
			e.printStackTrace();
		}

		return MODIFYINFO;
	}
	
	public void changeStatus() throws Exception {
		UserConfig userConfig = (UserConfig) request.getSession().getAttribute(
				"USERCONFIG");
		String checkvalue = request.getParameter("checkvalue");
		if (StringUtils.isNotBlank(checkvalue)) {
			if ("true".equals(checkvalue)) {
				userConfig.setStatus("1");
			} else {
				userConfig.setStatus("0");
			}
			try {
				userConfigManager.updateUserConfig(userConfig);
			} catch (JFossException e) {
				throw new JFossException(e);
			}
		}
	}

	public String getIndexPage() {
		return indexPage;
	}

	public void setIndexPage(String indexPage) {
		this.indexPage = indexPage;
	}
}
